<?php

namespace app\zyhsapi\service;

use XznsTools\cache\zyhs\CacheManageZyhs;

class CacheZyhs
{
    /**
     * @var \Redis 操作句柄
     */
    private static $handler = null;

    /**
     * 初始化 Redis
     * @return \Redis|null
     */
    public static function init()
    {
        if (is_null(self::$handler))
        {
            self::$handler = CacheManageZyhs::getInstance()->redisHandler;
        }

        return self::$handler;
    }

    /**
     * 读缓存
     * @param string $name
     * @param mixed $default
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public static function get(string $name, $default = false)
    {
        self::init();
        if (self::$handler)
        {
            $value = self::$handler->get(self::getCacheKey($name));

            return is_null($value) || false === $value ? $default : $value;
        }
        return $default;
    }

    /**
     * 设置缓存
     * @param string $name 缓存变量名
     * @param mixed $value 存储数据
     * @param null $expire 有效时间（秒）
     * @return bool|\Redis
     * @throws \RedisException
     */
    public static function set(string $name, $value, $expire = null)
    {
        self::init();
        if (self::$handler)
        {
            $key = self::getCacheKey($name);
            if ($expire)
            {
                $result = self::$handler->setex($key, $expire, $value);
            } else
            {
                $result = self::$handler->set($key, $value);
            }
            return $result;
        }
        return false;
    }

    /**
     * 自增缓存（针对数值缓存）
     * @param string $name 缓存变量名
     * @param int $step 步长
     * @return false|int
     * @throws \RedisException
     */
    public static function inc(string $name, int $step = 1)
    {
        self::init();
        if (self::$handler)
        {
            $key = self::getCacheKey($name);

            return self::$handler->incrby($key, $step);
        }
        return false;
    }

    /**
     * 自减缓存（针对数值缓存）
     * @param string $name 缓存变量名
     * @param int $step 步长
     * @return false|int
     * @throws \RedisException
     */
    public static function dec(string $name, int $step = 1)
    {
        self::init();
        if (self::$handler)
        {
            $key = self::getCacheKey($name);

            return self::$handler->decrby($key, $step);
        }
        return false;
    }

    /**
     * 删除缓存
     * @access public
     * @param string $name 缓存标识
     * @return boolean
     * @throws \RedisException
     */
    public static function rm(string $name)
    {
        self::init();
        if (self::$handler)
        {
            $key = self::getCacheKey($name);

            return self::$handler->delete($key);
        }
        return false;
    }

    /**
     * 获取缓存key
     * @param string $name
     * @return string
     */
    private static function getCacheKey(string $name)
    {
        return 'zyhs_cache:' . $name;
    }
}